package com.yuexia.sell.controller;

import com.yuexia.sell.converter.OrderFromToOrderDTOConverter;
import com.yuexia.sell.dto.OrderDTO;
import com.yuexia.sell.enums.ResultEnum;
import com.yuexia.sell.exception.SellException;
import com.yuexia.sell.from.OrderFrom;
import com.yuexia.sell.service.Interface.OrderService;
import com.yuexia.sell.util.ReultVoUtil;
import com.yuexia.sell.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author itmrchen
 * @date 2018/7/13 0013 上午 10:52
 * @desc ctrate by YUE XIA
 */
@RestController
@RequestMapping("/buyer/order")
@Slf4j
public class BuyerOrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    public ResultVo<Map<String,String>> create (@Valid OrderFrom orderFrom,
                                                  BindingResult bindingResult){

        if (bindingResult.hasErrors()){
            log.error("[订单创建]  订单接收参数错误，orderFrom {}",orderFrom);
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }

        OrderDTO orderDTO = OrderFromToOrderDTOConverter.converter(orderFrom);
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
            log.error("[订单创建] 购物车为空");
            throw new SellException(ResultEnum.CART_EMPTY);
        }
        orderDTO = orderService.create(orderDTO);

        Map<String,String> map = new HashMap<>();
        map.put("orderId",orderDTO.getOrderId());

        return ReultVoUtil.success(map);
    }
}
